import { forEach as _forEach } from 'lodash';
import { result as lvResult } from './result';

export function flatMap<T>(
  data: T[],
  pathFn: string | ((...args: any[]) => any) | null = null,
  traverse: boolean = false,
  childrenKey: string = 'children',
): Map<any, T> {
  const map = new Map<any, T>();

  const flatChildren = (source: T): void => {
    _forEach(lvResult(source, childrenKey), (item): void => {
      item.parent = source;
      map.set(lvResult(item, pathFn), item);
      flatChildren(item);
    });
  };

  _forEach(data, (item): void => {
    // tslint:disable-next-line
    item.parent = null;
    map.set(lvResult(item, pathFn), item);
    if (traverse) {
      flatChildren(item);
    }
  });

  return map;
}
